﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Text;
using WebApi;

namespace web
{

    public class Startup
    {

        public Startup(IConfiguration configuration)
        {
            this.Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            //https://www.shuzhiduo.com/A/E35pxEOA5v/
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Console.OutputEncoding = Encoding.GetEncoding("GB2312");
            Console.InputEncoding = Encoding.GetEncoding("GB2312");

            app.UseMiddleware<CorsMiddleware>();

            app.UseDeveloperExceptionPage();
            //https://www.shuzhiduo.com/A/E35pxEOA5v/
            app.UseForwardedHeaders();

            app.UseRouting();
            app.UseEndpoints(config => config.MapControllers());
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseFastIMServer(new ImServerOptions
            {
                Redis = new FreeRedis.RedisClient(Configuration["ImServerOption:RedisClient"]),
                Servers = Configuration["ImServerOption:Servers"].Split(";"),
                Server = Configuration["ImServerOption:Server"]
            });
            ImHelper.Initialization(new ImClientOptions
            {
                Redis = new FreeRedis.RedisClient(Configuration["ImClientOption:RedisClient"]),
                Servers = Configuration["ImClientOption:Servers"].Split(";")
            });

            ImHelper.Instance.OnSend += (s, e) =>
                Console.WriteLine($"ImClient.SendMessage(server={e.Server},senderClientId={e.SenderClientId},receiveClientId={e.ReceiveClientId},channel={e.Channel},data={JsonConvert.SerializeObject(e.Message)})");

            ImHelper.EventBus(
                async t =>
                {
                    // Console.WriteLine(t.clientId + "上线了");
                    var onlineUids = ImHelper.GetClientListByOnline();
                    await ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了", type:FastIM.MsgType.Online);
                },
                t => Console.WriteLine(t.clientId + "下线了"));
        }
    }
}
